//
//  homeViewController.m
//  giuseppe
//
//  Created by Apple on 15/7/13.
//  Copyright (c) 2015年 GiantUmbrella. All rights reserved.
//

#import "homeViewController.h"

#import "shoppingCartViewController.h"
#import "productDetailsViewController.h"

//Model
#import "myDataAccess.h"
#import "homePageModel.h"
#import "bannerImageModel.h"

//view
#import "goodsCollectionViewCell.h"
#import "schoolUniformHeaderView.h"

#import "userManager.h"

@interface homeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>{
    
    UITableView *homeTableView;
 
    NSArray *array;
    UIPageControl *_pageControl;
    NSMutableArray *slideImages;
    
    NSMutableArray *bannerImageModelArray;
    NSMutableArray *homePageModelArray;
    
    UICollectionView *homeCollectionView;
}

@end

@implementation homeViewController

#pragma mark lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    //设置原生导航栏隐藏
    self.navigationController.navigationBarHidden = YES;
    
    //自定义的导航栏
    UIView *navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    navView.backgroundColor = [UIColor whiteColor];
    navView.alpha = 0.90;
    //logo图片
    UIImageView *logoImage = [[UIImageView alloc]initWithFrame:CGRectMake(50, 35, 150, 20)];
    logoImage.image = [UIImage imageNamed:@"logoImage"];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, 33, 27, 16);
    [backButton setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    //右侧购物车按钮
    UIButton *shoppingCartButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shoppingCartButton setFrame:CGRectMake(kScreenWidth-90, 20, 70, 50)];
    [shoppingCartButton setImage:[UIImage imageNamed:@"shoppingCartButton"] forState:UIControlStateNormal];
    [shoppingCartButton addTarget:self action:@selector(shoppingCart) forControlEvents:UIControlEventTouchUpInside];
    

    [self _initHomeCollectionView];

    [navView addSubview:logoImage];

    [navView addSubview:backButton];
    [navView addSubview:shoppingCartButton];
    [self.view addSubview:navView];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [self.navigationController setToolbarHidden:YES animated:YES];
    //在自定义返回按钮情况下设置可以侧滑返回
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
    }
}


- (void)loadData{
    
//    NSString *userId = [[userManager shardInfo].userArray[0] objectForKey:@"userIdentityNumber"];
 
    NSString *userId = @"1";
    NSDictionary *paras = @{@"userId":userId};
    
    NSLog(@"paras%@",paras);
    
    //调用请求
    [[myDataAccess shardWebUtil] gettingHomePageInfoWithURLString:kNetPath_Code_homePageInfo  andParas:paras andTransferGottenData:^(id obj, NSError *error)  {
        
        NSLog(@"%@",obj);
        
        if (obj) {
  
            NSArray *imageArray = [obj objectForKey:@"adList"];
            bannerImageModelArray = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in imageArray) {
                
                bannerImageModel *imageModel = [bannerImageModel initWithDicAttributes:dic];
                [bannerImageModelArray addObject:imageModel];

            }
            
            NSArray *dataArray = [obj objectForKey:@"dataList"];
            homePageModelArray = [[NSMutableArray alloc]init];
            for (NSDictionary *dic in dataArray) {
                
                homePageModel *model = [homePageModel initWithDicAttributes:dic];
                [homePageModelArray addObject:model];
                
            }
            
            [homeCollectionView.legendHeader endRefreshing];
            [homeCollectionView reloadData];
 
        }else{
  
        }

    }];

}

#pragma mark viewLoad
- (void)_initHomeCollectionView{
    
    
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(moveImage) userInfo:self repeats:YES];

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(kScreenWidth/2, 600);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    [flowLayout setHeaderReferenceSize:CGSizeMake(kScreenWidth,300)];
//    flowLayout.headerReferenceSize = CGSizeMake(self.view.bounds.size.width, 500);
    
    
    homeCollectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
    homeCollectionView.backgroundColor = [UIColor whiteColor];
    
    homeCollectionView.dataSource = self;
    homeCollectionView.delegate = self;

    //注册单元格
    [homeCollectionView registerClass:[goodsCollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell"];
    //注册头视图
    [homeCollectionView registerClass:[schoolUniformHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    [self.view addSubview:homeCollectionView];
    

    __weak __typeof(self) weakSelf = self;
    
    [homeCollectionView  addLegendHeaderWithRefreshingBlock:^{
        
        [weakSelf loadData];
        
    }];
    
    [homeCollectionView.legendHeader beginRefreshing];
    
    
    
    //    //Masory布局
    //    [_displayScrollView mas_makeConstraints:^(MASConstraintMaker *make){
    //        make.top.mas_equalTo(self.view);
    //        make.size.mas_equalTo(CGSizeMake(kScreenWidth, 300));
    //    }];
    //
    //
    //    [_pageControl mas_makeConstraints:^(MASConstraintMaker *make){
    //        make.bottom.mas_equalTo(_displayScrollView);
    //        make.centerX.mas_equalTo(self.view);
    //        make.size.mas_equalTo(CGSizeMake(200, 30));
    //    }];
    
    

}


#pragma mark - UICollectionViewDataSource Methods
#pragma mark 设置某个分组有多少行
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return homePageModelArray.count;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

#pragma mark 设置某个Item显示什么内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *ID = @"collectionViewCell";
    
    goodsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];

    cell.imageView.frame = CGRectMake(0, 0, kScreenWidth/2, 300);
    cell.nameLabel.frame = CGRectMake(0, 300, kScreenWidth/2, 20);
    cell.soldNumberLabel.frame = CGRectMake(0, 320, kScreenWidth/2, 20);
    cell.addShoppingCartButton.frame = CGRectMake(kScreenWidth/2/2-30, 340, 60, 25);
    cell.priceLabel.frame = CGRectMake(60/2-15/2, 2.5, 30, 10);
    cell.priceLabel.adjustsFontSizeToFitWidth = YES;
    cell.model = homePageModelArray[indexPath.row];

    return cell;
}

#pragma mark 处理点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"我被点击了");
}

#pragma mark - UICollectionViewDelegateFlowLayout Method
#pragma mark 设置item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return CGSizeMake(kScreenWidth/2, 380);
}


//设置头尾部内容
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    UICollectionReusableView *reusableView =nil;
    if (kind ==UICollectionElementKindSectionHeader) {
        //定制头部视图的内容

        schoolUniformHeaderView *headerView = (schoolUniformHeaderView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        
        headerView.frame = CGRectMake(0, 0, kScreenWidth, 400);
        
        
        _displayScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 300)];
        _displayScrollView.backgroundColor = [UIColor whiteColor];
        _displayScrollView.contentSize = CGSizeMake(kScreenWidth * (bannerImageModelArray.count), 200);
        _displayScrollView.pagingEnabled = YES;
        _displayScrollView.showsHorizontalScrollIndicator = NO;
        _displayScrollView.delegate = self;
        _displayScrollView.bounces = NO;
        
        
        for (int i = 0;i<bannerImageModelArray.count;i++) {
        
            UIImageView *bannerImage = [[UIImageView alloc]init];
            bannerImage.frame = CGRectMake(kScreenWidth*i, 0, kScreenWidth, 200);
            NSString *imageURLString = [bannerImageModelArray[i] bannerImageUrl];
            [bannerImage sd_setImageWithURL:[NSURL URLWithString:imageURLString] placeholderImage:[UIImage imageNamed:@"1"]];
            [_displayScrollView addSubview:bannerImage];
        
        }
        
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(kScreenWidth/2-100, 250, 200, 30)];
        
        // 设置总共有多少页 numberOfPages
        _pageControl.numberOfPages = bannerImageModelArray.count;
        
        
        // 设置分页控件的颜色
        _pageControl.pageIndicatorTintColor = [UIColor grayColor];
        
        
        // 设置分页控件选中点的颜色
        _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
            
        [_pageControl addTarget:self action:@selector(turnPage) forControlEvents:UIControlEventTouchUpInside];
        _pageControl.currentPage = 0;
            
        
        [headerView addSubview:_displayScrollView];
        [headerView addSubview:_pageControl];

        reusableView = headerView;

        
        
    }
    return reusableView;
}





//- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
//{
//    return UIEdgeInsetsMake(0, 0, 0, 0);
//}

//#pragma mark 设置footer和header
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
//{
//    if (kind == UICollectionElementKindSectionHeader) {
//        // 去重用队列取可用的header
//        MyHeader *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
//        // 使用
//        reusableView.headerImage.image = [UIImage imageNamed:@"屏幕快照 2014-0 9.30.50 9-11 上午.png"];
//        // 返回
//        return reusableView;
//    }else{
//        // 去重用队列取可用的footer
//        MyFooter *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footerView" forIndexPath:indexPath];
//        // 使用
//        reusableView.backgroundColor = [UIColor redColor];
//        // 返回
//        return reusableView;
//        
//    }
//}
//
//#pragma mark 设置header和footer高度
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
//{
//    return CGSizeMake(self.view.bounds.size.width, 70);
//}
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
//{
//    return CGSizeMake(self.view.bounds.size.width, 70);
//}
//
//



#pragma mark - scrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    int currentPage = _displayScrollView.contentOffset.x / kScreenWidth;
    _pageControl.currentPage = currentPage;
    
}



#pragma mark - buttonAction

- (void)turnPage{
    
    
}

//定时器事件
- (void)moveImage{
    
    long page = _pageControl.currentPage; // 获取当前的page
//    NSLog(@"bannerImagePage:%ld",page+1);
    page++;
    
    if (page == bannerImageModelArray.count) {
        page = 0;
    }
    
    [_displayScrollView setContentOffset:CGPointMake(kScreenWidth*page, 0) animated:YES];
    _pageControl.currentPage = page;
    
    [self turnPage];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)shoppingCart{
    
    shoppingCartViewController  *shoppingCartCol = [[shoppingCartViewController alloc]init];
    [self.navigationController pushViewController:shoppingCartCol animated:YES];
    
}

//商品详情
- (void)pushDetails{
    
    productDetailsViewController *productDetailsVC = [[productDetailsViewController alloc]init];
    [self.navigationController pushViewController:productDetailsVC animated:YES];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
